﻿<template>
  <div id="cesiumContainer" style="width: 100%; height: 100vh;"></div>
</template>

<script setup>
import { onMounted } from 'vue';
import {
  Ion,
  Viewer,
  Cartesian3,
  Color,
  PointGraphics,
  PolylineGraphics,
  PolygonGraphics,
  GeometryInstance,
  PolylineGeometry,
  PolygonGeometry,
  Primitive,
  PerInstanceColorAppearance,
  ColorGeometryInstanceAttribute,
  PolylineMaterialAppearance,
  Material,
  EllipsoidSurfaceAppearance,
  PointPrimitiveCollection,
  BillboardCollection,
  Cartesian2
} from "cesium";
import "cesium/Build/Cesium/Widgets/widgets.css";

onMounted(() => {
  // 设置 Cesium Ion 访问令牌
  Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhNmQ5NDYyNi1lZTdhLTRiYTItODFiZi1mYzNiYWNjNDFjMzgiLCJpZCI6NTk3MTIsImlhdCI6MTY2MDE4MDAyNX0.bDTaHEah0hRjUyJWz0hyxIL0Fg63awPXV26OmQ5MCdM';

  const viewer = new Viewer('cesiumContainer', {
    animation: false, // 移除动画控件
    timeline: false, // 移除时间轴控件
    geocoder: false, // 移除地理编码控件
    homeButton: false, // 移除主页按钮
    sceneModePicker: false, // 移除场景模式选择器
    selectionIndicator: false, // 移除选择指示器
    fullscreenButton: false, // 移除全屏按钮
    vrButton: false // 移除 VR 按钮
  });

  // ==================== 使用 Entity API 添加点线面 ====================

  // 1. 使用 Entity 添加点
  // 红色圆点 - 北京
  viewer.entities.add({
    id: 'entity-point-beijing',
    name: '北京 - Entity点',
    position: Cartesian3.fromDegrees(116.3974, 39.9093), // 经度，纬度
    point: new PointGraphics({
      pixelSize: 15, // 点的像素大小
      color: Color.RED, // 点的颜色
      outlineColor: Color.WHITE, // 边框颜色
      outlineWidth: 2, // 边框宽度
      heightReference: 0 // 高度参考（贴地）
    })
  });

  // 蓝色圆点 - 上海
  viewer.entities.add({
    id: 'entity-point-shanghai',
    name: '上海 - Entity点',
    position: Cartesian3.fromDegrees(121.4737, 31.2304),
    point: new PointGraphics({
      pixelSize: 20,
      color: Color.BLUE,
      outlineColor: Color.YELLOW,
      outlineWidth: 3
    })
  });

  // 2. 使用 Entity 添加线
  // 红色线条 - 连接北京和上海
  viewer.entities.add({
    id: 'entity-line-beijing-shanghai',
    name: '北京-上海连线 - Entity线',
    polyline: new PolylineGraphics({
      positions: [
        Cartesian3.fromDegrees(116.3974, 39.9093), // 北京
        Cartesian3.fromDegrees(121.4737, 31.2304)  // 上海
      ],
      width: 5, // 线条宽度
      clampToGround: true, // 贴地显示
      material: Color.RED // 线条材质颜色
    })
  });

  // 绿色折线 - 多个点的连线
  viewer.entities.add({
    id: 'entity-polyline-multiple',
    name: '多点连线 - Entity折线',
    polyline: new PolylineGraphics({
      positions: [
        Cartesian3.fromDegrees(110, 35),
        Cartesian3.fromDegrees(115, 35),
        Cartesian3.fromDegrees(115, 40),
        Cartesian3.fromDegrees(120, 40),
        Cartesian3.fromDegrees(120, 35)
      ],
      width: 8,
      clampToGround: true,
      material: Color.GREEN
    })
  });

  // 3. 使用 Entity 添加面
  // 蓝色半透明多边形
  viewer.entities.add({
    id: 'entity-polygon-blue',
    name: '蓝色多边形 - Entity面',
    polygon: new PolygonGraphics({
      hierarchy: [
        Cartesian3.fromDegrees(105, 30),
        Cartesian3.fromDegrees(110, 30),
        Cartesian3.fromDegrees(110, 35),
        Cartesian3.fromDegrees(105, 35)
      ],
      material: Color.BLUE.withAlpha(0.5), // 半透明蓝色
      outline: true, // 显示边框
      outlineColor: Color.BLUE, // 边框颜色
      extrudedHeight: 50000 // 拉伸高度（米）
    })
  });

  // 红色多边形（带洞）
  viewer.entities.add({
    id: 'entity-polygon-with-hole',
    name: '带洞多边形 - Entity面',
    polygon: new PolygonGraphics({
      hierarchy: {
        positions: [
          // 外边界
          Cartesian3.fromDegrees(125, 30),
          Cartesian3.fromDegrees(135, 30),
          Cartesian3.fromDegrees(135, 40),
          Cartesian3.fromDegrees(125, 40)
        ],
        holes: [
          // 内部洞
          {
            positions: [
              Cartesian3.fromDegrees(128, 33),
              Cartesian3.fromDegrees(132, 33),
              Cartesian3.fromDegrees(132, 37),
              Cartesian3.fromDegrees(128, 37)
            ]
          }
        ]
      },
      material: Color.RED.withAlpha(0.6),
      outline: true,
      outlineColor: Color.DARKRED
    })
  });

  // ==================== 使用 Primitive API 添加点线面 ====================

  // 4. 使用 Primitive 添加点
  // 创建点集合 - 使用 PointPrimitiveCollection
  const pointCollection = new PointPrimitiveCollection();

  // 添加黄色点
  pointCollection.add({
    position: Cartesian3.fromDegrees(100, 25), // 广州附近
    color: Color.YELLOW,
    pixelSize: 20,
    outlineColor: Color.BLACK,
    outlineWidth: 2,
    id: 'primitive-point-1'
  });

  // 添加紫色点
  pointCollection.add({
    position: Cartesian3.fromDegrees(103, 28), // 成都附近
    color: Color.PURPLE,
    pixelSize: 25,
    outlineColor: Color.WHITE,
    outlineWidth: 3,
    id: 'primitive-point-2'
  });

  // 将点集合添加到场景
  viewer.scene.primitives.add(pointCollection);

  // 5. 使用 Primitive 添加线
  // 创建线几何实例
  const polylineInstances = [
    new GeometryInstance({
      geometry: new PolylineGeometry({
        positions: [
          Cartesian3.fromDegrees(90, 20),
          Cartesian3.fromDegrees(95, 25),
          Cartesian3.fromDegrees(100, 20)
        ],
        width: 10.0
      }),
      attributes: {
        color: ColorGeometryInstanceAttribute.fromColor(Color.ORANGE)
      },
      id: 'primitive-polyline-1'
    })
  ];

  // 添加线Primitive到场景
  viewer.scene.primitives.add(new Primitive({
    geometryInstances: polylineInstances,
    appearance: new PolylineMaterialAppearance({
      material: Material.fromType('Color', {
        color: Color.ORANGE
      })
    })
  }));

  // 6. 使用 Primitive 添加面
  // 创建多边形几何实例
  const polygonInstances = [
    new GeometryInstance({
      geometry: new PolygonGeometry({
        polygonHierarchy: {
          positions: [
            Cartesian3.fromDegrees(85, 15),
            Cartesian3.fromDegrees(95, 15),
            Cartesian3.fromDegrees(95, 25),
            Cartesian3.fromDegrees(85, 25)
          ]
        },
        extrudedHeight: 100000 // 拉伸高度
      }),
      attributes: {
        color: ColorGeometryInstanceAttribute.fromColor(Color.CYAN.withAlpha(0.7))
      },
      id: 'primitive-polygon-1'
    }),
    new GeometryInstance({
      geometry: new PolygonGeometry({
        polygonHierarchy: {
          positions: [
            Cartesian3.fromDegrees(75, 35),
            Cartesian3.fromDegrees(85, 35),
            Cartesian3.fromDegrees(80, 45)
          ]
        }
      }),
      attributes: {
        color: ColorGeometryInstanceAttribute.fromColor(Color.MAGENTA.withAlpha(0.8))
      },
      id: 'primitive-polygon-2'
    })
  ];

  // 添加面Primitive到场景
  viewer.scene.primitives.add(new Primitive({
    geometryInstances: polygonInstances,
    appearance: new EllipsoidSurfaceAppearance({
      material: Material.fromType('Color', {
        color: Color.CYAN.withAlpha(0.5)
      }),
      translucent: true
    })
  }));

  // 设置相机视角，显示所有添加的元素
  // 计算所有图形的边界，设置最佳观察位置
  // 图形分布范围：经度 75-135，纬度 15-45
  /*viewer.camera.setView({
    destination: Cartesian3.fromDegrees(105, 30, 3000000), // 经度，纬度，高度（米）
    orientation: {
      heading: 0.0, // 方向角（正北方向）
      pitch: -0.7,  // 俯仰角（向下看）
      roll: 0.0     // 翻滚角
    }
  });*/

  // 或者使用 flyTo 方法，自动计算最佳视角（备用方案）
  viewer.flyTo(viewer.entities);

  // ==================== 辅助功能 ====================

  // 点击事件处理 - 用于查看点击的实体信息
  viewer.cesiumWidget.screenSpaceEventHandler.setInputAction(function onLeftClick(event) {
    const pickedObject = viewer.scene.pick(event.position);
    if (pickedObject && pickedObject.id) {
      console.log('点击的实体:', pickedObject.id);
      // 如果是Entity，可以获取更多信息
      if (pickedObject.id.name) {
        console.log('实体名称:', pickedObject.id.name);
      }
    }
  }, 2); // 2 代表鼠标左键点击事件
});
</script>

<style>
/* 隐藏页面底部的 Cesium logo 和数据归属 */
.cesium-viewer .cesium-widget-credits {
  display: none !important; /* 隐藏整个 Cesium 控件 */
}

/* 隐藏 右上角的 Imagery 和 Navigation instructions */
.cesium-viewer .cesium-viewer-toolbar {
  display: none !important; /* 隐藏工具栏 */
}
</style>
